<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0, user-scalable=no">
    <meta name="format-detection" content="telephone=no, email=no">
    <meta name="HandheldFriendly" content="true">
    <title>确定设备进去配网模式</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <link rel="stylesheet" href="__STATIC__/frozenui-2.0.0/release/css/frozenui.css"/>
    <link rel="stylesheet" href="__STATIC__/frozenui-2.0.0/release/demo/css/style.css">

</head>
<body ontouchstart>
<section class="ui-container">
    <section id="layout">
        <div class="demo-item">
            <div class="demo-block">
                <div class="ui-flex ui-flex-pack-center">
                    <div>
                        <img id="img" width="100%">
                    </div>
                </div>
                <div class="demo-block">
                    <div class="ui-whitespace">
                        <p id="des" class="ui-txt-justify"
                           style="font-size: larger ;  margin-top: 60px ">
                            &nbsp;&nbsp;&nbsp;&nbsp;</p>
                    </div>
                </div>
                <div class="ui-btn-wrap ui-btn-wrap-middle" style="margin-top: 180px" id="btnStart">
                    <button class="ui-btn-lg-nowhole ui-btn-primary">
                        开始配网
                    </button>
                </div>

                <div id="load" class="demo-block">
                    <div class="ui-loading-block show">
                        <div class="ui-loading-cnt">
                            <i class="ui-loading-bright"></i>
                            <p>正在加载中...</p>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </section>
</section>

</body>
<script>


    //base64解密方法
    function Base64() {

        // private property
        _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        // public method for encoding
        this.encode = function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        }

        // public method for decoding
        this.decode = function (input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        }

        // private method for UTF-8 encoding
        _utf8_encode = function (string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }
            return utftext;
        }

        // private method for UTF-8 decoding
        _utf8_decode = function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;
            while (i < utftext.length) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    }


    // 对浏览器的UserAgent进行正则匹配，不含有微信独有标识的则为其他浏览器
    var useragent = navigator.userAgent;
    if (useragent.match(/WindowsWechat/) == 'WindowsWechat' || useragent.match(/MicroMessenger/i) != 'MicroMessenger') {
        // 这里警告框会阻塞当前页面继续加载
        //alert('已禁止本次访问：您必须使用微信内置浏览器访问本页面！');
        document.head.innerHTML = '<title>抱歉，出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">';
        document.body.innerHTML = '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>';
    }

    var chartData = {$deviceInfo};
    //alert(JSON.stringify(chartData.user))

    var p = document.getElementById('des');
    //显示设备进行配网状态设置的提示
    p.innerHTML = p.innerText + chartData.message
    //图片
    var img = document.getElementById('img');
    img.src = chartData.icon


    $("#btnStart").click(function () {

        wx.invoke('configWXDeviceWiFi', {}, function (res) {
            var err_msg = res.err_msg;
            if (err_msg === 'configWXDeviceWiFi:ok') {

                alert('配网成功！！！');
                //关闭这个窗口，返回微信公众号主页
                //wx.closeWindow();

                //配置成功,获取本地广播
                wx.invoke('openWXDeviceLib', {
                    'connType': 'lan',
                    'brandUserName': 'gh_4248324a4d02'
                }, function (res) {
                     alert(res.err_msg);
                    //alert("openWXDeviceLib：" + JSON.stringify(res));
                });
                wx.invoke('startScanWXDevice', {'connType': 'lan'}, function (res) {
                    //console.log('startScanWXDevice', res);
                    //alert("开始扫描：" + JSON.stringify(res));
                });
                wx.on('onScanWXDeviceResult', function (res) {
                    //alert("get Data");
                    //alert("扫描到1个设备，自定义消息是：" + JSON.stringify(res.devices[0]));
                    //自己解析一下res，里面会有deviceid,扫描设备的目的就是为了得到这个
                    //然后就可以开始绑定了
                    var base = new Base64();
                    var info = base.decode(res.devices[0].deviceId);
                    var bindInfo = JSON.parse(info);
                    bindInfo.token = chartData.user.token;
                    $.ajax({
                        type: 'POST',
                        url: "{:url('ReadyDeviceActivity/bindDevice')}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(bindInfo),
                        success: function (data) {
                            alert("" + data.msg);
                            //关闭这个窗口，返回微信公众号主页
                            wx.closeWindow();
                        }
                    });
                });
            } else if (err_msg === 'configWXDeviceWiFi:cancle') {
                //配置失败
                alert('配置失败!' + err_msg);
            }
        });
    });

    wx.config(chartData.wechat)

        
    // echo 'start config';
    wx.ready(function () {

        //隐藏右上角的复制链接、分享链接到qq浏览器等! https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
        //要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
        wx.hideMenuItems({
            menuList: [
                "menuItem:editTag",
                "menuItem:delete",
                "menuItem:copyUrl",
                "menuItem:originPage",
                "menuItem:readMode",
                "menuItem:openWithQQBrowser",
                "menuItem:openWithSafari",
                "menuItem:share:email",
                "menuItem:share:brand",
            ]
        });

        // 在这里调用 API
        wx.checkJsApi({
            jsApiList: ['configWXDeviceWiFi'],
            //成功初始化之后，隐藏加载
            success: function (res) {
                $("#load").hide();
            },
        });
    });

    wx.error(function (res) {
        $("#load").hide();
        alert("初始化失败:" + JSON.stringify(res));
    });


</script>
</html>